﻿using System.Collections.Generic;
using System.Device.Location;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Renren.Models;
using Renren.ServiceProviders;
using Renren.ViewModels;

namespace Renren.Services
{
    public static class PlaceService
    {
        private static bool handlerAttached = false;
        private static bool handlerCalled = false;
        private static DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ResponseModel<PlaceModel>));

        private static GeoCoordinateWatcher _geoWatcher;
        public static GeoCoordinateWatcher GeoWatcher
        {
            get
            {
                if (_geoWatcher == null)
                {
                    _geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                    _geoWatcher.MovementThreshold = 20;
                    _geoWatcher.Start();
                }
                return _geoWatcher;
            }
        }

        public static void GetPlaces()
        {
            if (GeoWatcher.Status == GeoPositionStatus.Ready)
            {
                GetPlaces(GeoWatcher.Position.Location);
            }
            else
            {
                // If geo watcher is not ready, add a handler to get places async
                if (!handlerAttached)
                {
                    handlerAttached = true;
                    GeoWatcher.PositionChanged += (s, e) =>
                        {
                            // Only call get places async at most once
                            if (!handlerCalled)
                            {
                                handlerCalled = true;
                                GetPlaces(e.Position.Location);
                            }
                        };
                }
            }
        }

        private static void GetPlaces(GeoCoordinate location)
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("location", location.Latitude + "," + location.Longitude);
            parameters.Add("radius", "500");
            parameters.Add("language", "zh-CN");
            parameters.Add("sensor", "true");
            Service.SendRequest(
                ServiceProviderType.Google,
                parameters,
                result =>
                {
                    App.ViewModel.PlaceList.Clear();
                    var places = (serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(result))) as ResponseModel<PlaceModel>).Items;
                    foreach (var place in places)
                    {
                        App.ViewModel.PlaceList.Add(new PlaceViewModel(place));
                    }
                });
        }
    }
}
